﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MachineQA.Model;

namespace MachineQA
{
    /// <summary>
    /// Interaction logic for EnergiesTab.xaml
    /// </summary>
    public partial class EnergiesTab : UserControl
    {
        public EnergiesTab()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            AddPhotonsAndElectronsIfNeeded();
            InitializeEnergyListbox();
            ModalityComboBox.DataContext = Constants.entities.Modalities.Select((i) => i.Name);
        }

        private void InitializeEnergyListbox()
        {
            EnergiesListbox.Items.Clear();
            foreach (Energy curEnergy in Constants.entities.Energies.OrderBy((i) => i.Modality.Name).OrderBy((i) => i.value).ToList())
            {

                StackPanel newStack = new StackPanel();
                newStack.Orientation = Orientation.Horizontal;
                Label newLabel = new Label();
                newLabel.Content = curEnergy.value;
                Label newLabel2 = new Label();
                switch (curEnergy.Modality.Name)
                {
                    case "photons":
                        newLabel2.Content = "MV";
                        break;
                    case "electrons":
                        newLabel2.Content = "MeV";
                        break;
                    default:
                        newLabel2.Content = curEnergy.Modality.Name;
                        break;
                }
                newLabel2.Margin = new Thickness(2, 0, 0, 0);
                newStack.Children.Add(newLabel);
                newStack.Children.Add(newLabel2);
                EnergiesListbox.Items.Add(newStack);
            }
        }

        private void AddPhotonsAndElectronsIfNeeded()
        {
            if (Constants.entities.Modalities.Where((i) => i.Name == "photons").Count() == 0)
            {
                try
                {
                    Modality photonModality = new Modality();
                    photonModality.Name = "photons";
                    Constants.entities.AddToModalities(photonModality);
                    Constants.entities.SaveChanges();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Problem while adding missing photon modality:\n" + ex.Message);
                }
            }
            if (Constants.entities.Modalities.Where((i) => i.Name == "electrons").Count() == 0)
            {
                try
                {
                    Modality electronModality = new Modality();
                    electronModality.Name = "electrons";
                    Constants.entities.AddToModalities(electronModality);
                    Constants.entities.SaveChanges();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Problem while adding missing electron modality:\n" + ex.Message);
                }
            }
        }

        private void NewEnergyNameBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TryEnableSaveButton();
        }

        private void TryEnableSaveButton()
        {
            double enteredValue;
            if (double.TryParse(NewEnergyNameBox.Text, out enteredValue))
            {
                EnergySaveButton.IsEnabled = (NewEnergyNameBox.Text != string.Empty && (string)ModalityComboBox.SelectedItem != null &&
                                          (Constants.entities.Energies.Where(
                                                                              (i) => i.value == enteredValue &&
                                                                              i.Modality.Name == (string)ModalityComboBox.SelectedValue
                                                                            ).Count() == 0));
            }
            else
            {
                string value = NewEnergyNameBox.Text;
                if (value.Split('.').Count() < 3)
                {
                    if (value.Length > 0)
                    {
                        NewEnergyNameBox.TextChanged -= NewEnergyNameBox_TextChanged;
                        double num;
                        while (value.Length > 0 && !double.TryParse(value, out num))
                        {
                            value = value.Substring(0, value.Length - 1);
                        }
                        NewEnergyNameBox.Text = value;
                        MessageBox.Show("Entered a character that can't be part of a number. Please enter only numeric values." +
                            "Units will be generated automatically for photon and electron energies.");
                        NewEnergyNameBox.TextChanged += NewEnergyNameBox_TextChanged;
                    }
                }
                else
                {
                    MessageBox.Show("More than one decimal point was found. Value has been cleared please re-enter the value desired.");
                    NewEnergyNameBox.TextChanged -= NewEnergyNameBox_TextChanged;
                    NewEnergyNameBox.Text = "";
                    NewEnergyNameBox.TextChanged += NewEnergyNameBox_TextChanged;
                }
            }
        }

        private void EnergySaveButton_Click(object sender, RoutedEventArgs e)
        {
            Energy newEnergy = new Energy();
            newEnergy.value = double.Parse(NewEnergyNameBox.Text); // Save because already checked value in the TextChanged handler
            newEnergy.Modality = Constants.entities.Modalities.Where((i) => i.Name == (string)ModalityComboBox.SelectedValue).First();
            Constants.entities.AddToEnergies(newEnergy);
            try
            {
                Constants.entities.SaveChanges();
                EnergySaveButton.IsEnabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was a problem loading the new energy. Error: \n" + ex.Message);
            }
            InitializeEnergyListbox();
        }

        private void ModalityComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TryEnableSaveButton();
        }
    }
}
